<template>
  <view class="on-off-page">
    <Navbar title="监测电器" />
    <view class="row-title">
      <view class="row-title-left">
        <text class="appliance-name">{{ '设备' + deviceInfo.deviceCode }}</text>
      </view>
      <view class="row-title-right">
        <view class="contact-info">
          <text class="company-name">{{ deviceInfo.company }}</text>
        </view>
        <view class="contact-info">
          <text class="contact-name">{{ deviceInfo.person }}</text>
          <text class="contact-name">{{ deviceInfo.mobile }}</text>
          <image
            src="/static/img/consolePages/phone-icon.png"
            class="phone-icon"
            mode="widthFix"
            @click="callPhone(deviceInfo.mobile || '18551087487')"
          />
        </view>
      </view>
    </view>
    <view class="card-section">
      <!-- 运行状态时序图 -->
      <view class="section-title-chart">
        <text class="chart-title-text">运行状态</text>
      </view>
      <view class="chart-section section-state">
        <view class="chart-header-container">
          <!-- 日期选择器 -->
          <view class="chart-controls">
            <view class="control-btn" @click="showOperationCalendar = true">{{
              operationDate || '选择日期'
            }}</view>
          </view>
        </view>
        <!-- 图表 -->
        <view class="chart-container-a">
          <view class="y-axis-label y-axis-label-0">停机</view>
          <view class="y-axis-label y-axis-label-1">运行</view>
          <qiun-data-charts
            type="area"
            :opts="operationChartOpts"
            :chartData="operationChartData"
          />
        </view>
      </view>
      <!-- 用电趋势曲线区域图 -->
      <view class="section-title-chart">
        <text class="chart-title-text">用电趋势</text>
      </view>
      <view class="chart-section">
        <view class="chart-header">
          <view class="step">功率（kw）</view>
          <view class="chart-controls">
            <view class="control-btn" @click="showPowerCalendar = true">{{
              powerDate || '选择日期'
            }}</view>
          </view>
        </view>
        <view class="current-value">
          <view v-if="selectedIndexPower !== null">
            {{ powerDate }} {{ selectedXPower }}时
            <text class="highlight-value">{{ selectedYPower }}kw</text>
          </view>
          <view v-else></view>
        </view>
        <!-- 图表 -->
        <view class="chart-container-b">
          <qiun-data-charts
            type="area"
            :opts="powerChartOpts"
            :chartData="powerChartData"
            @getIndex="onPowerChartPointClick"
          />
        </view>
      </view>
    </view>

    <!-- 运行状态日期选择器弹窗 -->
    <tn-popup
      v-model="showOperationCalendar"
      open-direction="bottom"
      :custom-style="{ borderRadius: '32rpx 32rpx 0 0' }"
    >
      <tn-calendar
        v-model="operationDate"
        active-bg-color="#1ec8e1"
        active-text-color="#fff"
        min-date="2020-01-01"
        :max-date="maxDate"
        class="detail-calendar"
      />
    </tn-popup>

    <!-- 用电趋势日期选择器弹窗 -->
    <tn-popup
      v-model="showPowerCalendar"
      open-direction="bottom"
      :custom-style="{ borderRadius: '32rpx 32rpx 0 0' }"
    >
      <tn-calendar
        v-model="powerDate"
        active-bg-color="#1ec8e1"
        active-text-color="#fff"
        min-date="2020-01-01"
        :max-date="maxDate"
        class="detail-calendar"
      />
    </tn-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import Navbar from '@/components/Navbar.vue';
import { createRequest } from '@/utils/request';

// 运行状态时序图配置
const operationChartOpts = reactive({
  color: ['#1ec8e1'],
  enableScroll: false,
  legend: {
    show: false,
  },
  xAxis: {
    disableGrid: true,
    fontColor: 'rgba(255, 255, 255, 0.6)',
    rotateLabel: false,
    boundaryGap: 'justify',
    labelCount: 12,
    data: [{ min: 0, max: 12 }],
    itemCount: 12,
    fontSize: 10,
  },
  yAxis: {
    disabled: false,
    gridType: 'solid',
    dashLength: 0,
    data: [{ min: -1, max: 2 }],
    fontColor: 'rgba(255, 255, 255, 0.6)',
    fontSize: 16,
    gridColor: 'rgba(255, 255, 255, 0.1)',
    splitNumber: 3,
  },
  extra: {
    area: {
      type: 'step',
      width: 2,
      activeType: 'hollow',
      gradient: true,
      opacity: 0.2,
    },
  },
  dataLabel: false,
  dataPointShape: false,
  enableMarkLine: false,
  enableMarkPoint: false,
});

// 运行状态时序图数据
const operationChartData = ref({
  categories: [],
  series: [],
});

// 用电趋势曲线区域图配置
const powerChartOpts = reactive({
  color: ['#8b5cf6'],
  enableScroll: false,
  padding: [20, 20, 40, 20],
  legend: {
    show: false,
  },
  xAxis: {
    disableGrid: true,
    fontColor: 'rgba(255, 255, 255, 0.6)',
    rotateLabel: false,
    boundaryGap: 'justify',
    labelCount: 12,
    data: [{ min: 0, max: 12 }],
    itemCount: 12,
    fontSize: 10,
  },
  yAxis: {
    gridType: 'solid',
    dashLength: 0,
    data: [{ min: 0, max: 1000 }],
    fontColor: 'rgba(255, 255, 255, 0.6)',
    fontSize: 16,
    gridColor: 'rgba(255, 255, 255, 0.1)',
    splitNumber: 5,
  },
  extra: {
    area: {
      type: 'curve',
      opacity: 0.3,
      width: 2,
      gradient: true,
      activeType: 'hollow',
    },
  },
  dataLabel: false,
  dataPointShape: false,
  enableMarkLine: false,
  enableMarkPoint: false,
});

// 用电趋势曲线区域图数据
const powerChartData = ref({
  categories: [],
  series: [
    {
      name: '功率',
      data: [],
    },
  ],
});

// 日期选择器相关
function getTodayStr() {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(
    2,
    '0'
  )}-${String(today.getDate()).padStart(2, '0')}`;
}

// 日期格式转换函数：将 2025/08/05 转换为 2025-08-05
function formatDate(dateStr) {
  if (!dateStr) return '';
  // 如果已经是正确格式，直接返回
  if (dateStr.includes('-')) return dateStr;
  // 将 2025/08/05 转换为 2025-08-05
  return dateStr.replace(/\//g, '-');
}

const showOperationCalendar = ref(false);
const showPowerCalendar = ref(false);
const operationDate = ref(getTodayStr());
const powerDate = ref(getTodayStr());
const maxDate = computed(() => getTodayStr());

// 图表点击事件相关
const selectedIndexPower = ref(null);
const selectedXPower = ref(null);
const selectedYPower = ref(null);

function onPowerChartPointClick(e) {
  if (e?.currentIndex?.index != null) {
    const idx = e.currentIndex.index;
    selectedIndexPower.value = idx;
    selectedXPower.value = powerChartData.value.categories[idx];
    selectedYPower.value = powerChartData.value.series[0].data[idx];
  }
}

// 获取运行状态数据
const getOperationData = async () => {
  // 检查必要参数
  if (!deviceInfo.value.id) {
    return;
  }
  if (!operationDate.value) {
    return;
  }

  try {
    // 确保日期格式正确
    const formattedDate = formatDate(operationDate.value);
    const result = await createRequest(
      `/key-device/statusReports?keyDeviceId=${deviceInfo.value.id}&queryDate=${formattedDate}`,
      {
        method: 'get',
      }
    );

    if (result.code === 200 && result.data) {
      const statusPoints = result.data.statusPoints;

      if (statusPoints.length > 0) {
        // 检查是否为今天
        const today = new Date().toDateString();
        const queryDate = new Date(operationDate.value).toDateString();
        const isToday = today === queryDate;

        // 获取最后一个状态值
        const lastStatus = statusPoints[statusPoints.length - 1].status;

        // 补充结束时间点数据
        let endTime;
        if (isToday) {
          // 如果是今天，使用当前系统时间
          const now = new Date();
          endTime = `${now.getHours().toString().padStart(2, '0')}:${now
            .getMinutes()
            .toString()
            .padStart(2, '0')}`;
        } else {
          endTime = '24:00';
        }

        // 处理时间戳，提取时:分格式
        const categories = statusPoints.map(point => {
          const timestamp = new Date(point.timestamp);
          const hours = timestamp.getHours().toString().padStart(2, '0');
          const minutes = timestamp.getMinutes().toString().padStart(2, '0');
          return `${hours}:${minutes}`;
        });

        // 添加结束时间点
        categories.push(endTime);

        // 处理状态数据
        const seriesData = statusPoints.map(point => point.status);

        // 添加结束状态（与最后一个状态保持一致）
        seriesData.push(lastStatus);

        // 更新图表数据
        operationChartData.value = {
          categories: categories,
          series: [
            {
              name: '运行状态',
              data: seriesData,
            },
          ],
        };

        // 动态设置x轴
        operationChartOpts.xAxis.data[0].min = 0;
        operationChartOpts.xAxis.data[0].max = Math.max(
          0,
          categories.length - 1
        );

        // 根据数据量智能设置标签显示数量
        const dataLength = categories.length;
        const displayCount = Math.min(dataLength, 12);
        operationChartOpts.xAxis.labelCount = displayCount;
        operationChartOpts.xAxis.itemCount = displayCount;
      } else {
        operationChartData.value = {
          categories: [],
          series: [],
        };
      }
    }
  } catch (error) {
    console.error('获取运行状态数据失败:', error);
    operationChartData.value = {
      categories: [],
      series: [],
    };
  }
};

// 获取用电趋势数据
const getPowerData = async () => {
  // 检查必要参数
  if (!deviceInfo.value.id) {
    return;
  }
  if (!powerDate.value) {
    return;
  }

  try {
    // 确保日期格式正确
    const formattedDate = formatDate(powerDate.value);
    const result = await createRequest(
      `/key-device/${deviceInfo.value.id}/trend?date=${formattedDate}`,
      {
        method: 'get',
      }
    );

    if (result.code === 200 && result.data) {
      const trendData = result.data;

      if (Object.keys(trendData).length > 0) {
        // 将数据转换为数组格式，只取前12条
        const entries = Object.entries(trendData).slice(0, 12);

        // 处理时间轴，提取小时
        const categories = entries.map(([key]) => {
          // 从 "2025-08-25 10" 格式中提取小时部分
          const hour = key.split(' ')[1];
          return `${hour}时`;
        });

        // 处理功率数据
        const seriesData = entries.map(([, value]) =>
          Math.round(parseFloat(value) || 0)
        );

        // 更新图表数据
        powerChartData.value = {
          categories: categories,
          series: [
            {
              name: '功率',
              data: seriesData,
            },
          ],
        };

        // 动态设置y轴范围
        const maxPower = Math.max(...seriesData);
        const minPower = Math.min(...seriesData);
        const range = maxPower - minPower;

        if (range > 0) {
          powerChartOpts.yAxis.data[0].min = Math.floor(minPower - range * 0.1);
          powerChartOpts.yAxis.data[0].max = Math.ceil(maxPower + range * 0.1);
        } else if (maxPower > 0) {
          // 如果所有值都相同，设置一个合理的范围
          powerChartOpts.yAxis.data[0].min = 0;
          powerChartOpts.yAxis.data[0].max = Math.ceil(maxPower * 1.2);
        } else {
          // 如果没有数据，设置默认范围
          powerChartOpts.yAxis.data[0].min = 0;
          powerChartOpts.yAxis.data[0].max = 1000;
        }

        // 动态设置x轴
        powerChartOpts.xAxis.data[0].min = 0;
        powerChartOpts.xAxis.data[0].max = Math.max(0, categories.length - 1);

        // 根据数据量智能设置标签显示数量
        const dataLength = categories.length;
        const displayCount = Math.min(dataLength, 12);
        powerChartOpts.xAxis.labelCount = displayCount;
        powerChartOpts.xAxis.itemCount = displayCount;
      } else {
        powerChartData.value = {
          categories: [],
          series: [
            {
              name: '功率',
              data: [],
            }
          ],
        };
      }
    }
  } catch (error) {
    console.error('获取用电趋势数据失败:', error);
    powerChartData.value = {
      categories: [],
      series: [
        {
          name: '功率',
          data: [],
        },
      ]
    };
  }
};

// 保存传递过来的参数
const deviceInfo = ref({
  id: '',
  deviceCode: '',
  company: '',
  person: '',
  mobile: '',
});

// 获取页面参数
onLoad(options => {
  if (options) {
    deviceInfo.value = {
      id: decodeURIComponent(options.id || ''),
      deviceCode: decodeURIComponent(options.deviceCode || ''),
      company: decodeURIComponent(options.company || ''),
      person: decodeURIComponent(options.person || ''),
      mobile: decodeURIComponent(options.mobile || ''),
    };
  }

  // 页面加载完成后，等待下一个tick再获取数据
  // 确保 deviceInfo 已经设置完成
  nextTick(() => {
    // 延迟一点时间确保参数完全设置完成
    setTimeout(() => {
      if (deviceInfo.value.id) {
        getOperationData();
        getPowerData();
      }
    }, 100);
  });
});

// 拨打电话
function callPhone(phone) {
  if (phone) {
    uni.makePhoneCall({ phoneNumber: phone });
  }
}

// 监听日期变化，自动刷新数据
watch(operationDate, newDate => {
  // 转换日期格式
  if (newDate) {
    operationDate.value = formatDate(newDate);
  }

  // 日期变化时，延迟一点时间再检查日历状态
  setTimeout(() => {
    if (!showOperationCalendar.value) {
      getOperationData();
    }
  }, 100);
});

watch(powerDate, newDate => {
  // 转换日期格式
  if (newDate) {
    powerDate.value = formatDate(newDate);
  }

  // 日期变化时，延迟一点时间再检查日历状态
  setTimeout(() => {
    if (!showPowerCalendar.value) {
      getPowerData();
    }
  }, 100);
});

// 监听日历选择器关闭事件
watch(showOperationCalendar, (newVal, oldVal) => {
  // 当日历从打开变为关闭时，如果日期已变化则刷新数据
  if (oldVal && !newVal) {
    getOperationData();
  }
});

watch(showPowerCalendar, (newVal, oldVal) => {
  // 当日历从打开变为关闭时，如果日期已变化则刷新数据
  if (oldVal && !newVal) {
    getPowerData();
  }
});

onMounted(() => {
  // 页面挂载后的初始化工作（如果需要的话）
  // 数据获取已在 onLoad 中处理
});
</script>

<style scoped lang="scss">
.on-off-page {
  @include page-with-header;
  min-height: 100vh;
  background: #172869;
}
.row-title {
  margin: 32rpx;
  height: 120rpx;
  box-sizing: border-box;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10rpx;
  overflow: hidden;
}

.row-title-left {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #2e3e78;
}

.appliance-name {
  font-size: 32rpx;
  color: #ffffff;
  text-align: left;
  letter-spacing: 2rpx;
  font-weight: 500;
}

.row-title-right {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12rpx;
  background: #2e3e7894 58%;
  padding: 18rpx 36rpx;
  box-sizing: border-box;
}

.contact-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12rpx;
  width: 100%;
}

.company-name {
  font-size: 26rpx;
  color: #e8f4fd;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.contact-name {
  font-size: 26rpx;
  color: #ffffff;
  line-height: 1.4;
}

.phone-icon {
  width: 28rpx;
  transition: opacity 0.3s ease;
}

.phone-icon:active {
  opacity: 0.7;
}

.card-section {
  width: 100%;
  padding: 0 32rpx;
  box-sizing: border-box;
}
.section-title-chart {
  width: 100%;
  height: 68rpx;
  background-image: url('/static/img/homePages/chart-title.png');
  background-size: 100% 100%;
  margin-top: 20rpx;
}
.chart-title-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  letter-spacing: 3rpx;
  font-family: 'YouSheBiaoTiHei';
  line-height: 68rpx;
  margin-left: 60rpx;
}
.chart-section {
  width: 686rpx;
  height: 554rpx;
  background-image: url('/static/img/components/chart-section.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  overflow: hidden;
}
.section-state {
  height: 296rpx;
  background-image: url('/static/img/consolePages/chart-section-short.png');
}
.chart-header-container {
  width: 100%;
  height: 92rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 30rpx;
  box-sizing: border-box;
  position: relative;
  z-index: 10;
}

.chart-header {
  width: 100%;
  height: 66rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 0;
  box-sizing: border-box;
}

.step {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
}

.current-value {
  width: 610rpx;
  height: 40rpx;
  margin: 26rpx auto 10rpx;
  background-color: rgba(255, 255, 255, 0.1);
  padding: 4rpx 8rpx;
  box-sizing: border-box;
  text-align: center;
  line-height: 40rpx;
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
}

.highlight-value {
  color: #1ec8e1;
}

.chart-container-a {
  margin-left: 70rpx;
  width: 580rpx;
  height: 296rpx;
  position: relative;
  top: -100rpx;
  z-index: 1;
}

.y-axis-label {
  position: absolute;
  left: -40rpx;
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.6);
  z-index: 10;
}

.y-axis-label-0 {
  bottom: 34%;
}

.y-axis-label-1 {
  top: 30%;
}

.chart-container-b {
  margin-top: -20rpx;
}

// 日期选择器样式
.chart-controls {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  min-width: 260rpx;
  position: relative;
  z-index: 10;
}

.control-btn {
  padding: 4rpx 24rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  background: rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  z-index: 10;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
}

.detail-calendar {
  // padding: 0 60rpx 60rpx 0;
  box-sizing: border-box;
  color: #eee;
  // 你可以继续添加更多自定义样式
}

/* 日历组件样式优化 */
:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

// 清空calendar数据区域的padding
:deep(.tn-calendar__data) {
  box-sizing: border-box !important;
}

// 清空calendar星期文字的padding
:deep(.tn-calendar__week-text) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__operation) {
  box-sizing: border-box !important;
}
</style>
